require(dplyr)
require(tidyr)
require(countrycode)
require(stringr)
source("functions.R")

# GTI
dat <- readRDS("class.RDS")
dat <- dat[dat$country.class != "us",]
dat$country.class[dat$country.class %in% c("cn", "tw", "mo")] <- "cn"
dat_gti <- get_gti(dat, c(country_major, country_minor))

# Other index
dat_mids <- readRDS('data/data_mids.RDS')
dat_cinc <- readRDS('data/data_cinc.RDS')
dat_un <- readRDS('data/data_un.RDS') # UN vote
dat_atop <- readRDS('data/data_atop.RDS') # Alliance
dat_ss <- readRDS('data/data_ss.RDS') # Alliance
dat_lrm <- readRDS('data/data_lrm.RDS') # Fitted MIDS
dat_gc <- readRDS('data/data_gc.RDS') # Geo-political competition

dat_gti <- merge(dat_gti, dat_mids, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_cinc, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_un, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_atop, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_ss, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_lrm, by = c("country", "year"), all.x = TRUE)
dat_gti <- merge(dat_gti, dat_gc, by = c("country", "year"), all.x = TRUE)

dat_gti$ls <- 0
# non-allies are NA as they do not appear in ATOP
foe <- is.na(dat_gti$ally) | dat_gti$s_uw < median(dat_ss$s_uw, na.rm = TRUE)
dat_gti$ls <- dat_gti$cinc * foe
dat_gti$ls[!dat_gti$year %in% 1815:2016] <- NA

saveRDS(dat_gti, "data_index.RDS")
